package com.freexiaoyu.freevideoplay;

import android.app.Activity;
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaCodecList;
import android.media.MediaFormat;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.freexiaoyu.freevideoplay.ui.base.BaseActivity;

import java.io.IOException;
import java.io.InputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;

public class VideoFourActivity extends Activity implements SurfaceHolder.Callback {

    private static final String TAG = "MainActivity";
    private MediaCodec mediaCodec;
    private SurfaceHolder surfaceHolder;
    private boolean isDecoding = false;
    private Thread serverThread;
    private Thread decoderThread;
    private ByteBuffer psByteBuffer;

    private int mWidth = 1080;
    private int mHeight = 720;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_ffmpeg_two);

        SurfaceView surfaceView = findViewById(R.id.surfaceView);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);

        startServerThread();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            // 检查设备是否支持MPEG-2解码器
            boolean hasMpeg2Decoder = false;
            for (int i = 0; i < MediaCodecList.getCodecCount(); i++) {
                MediaCodecInfo codecInfo = MediaCodecList.getCodecInfoAt(i);
                if (!codecInfo.isEncoder()) {
                    String[] types = codecInfo.getSupportedTypes();
                    for (String type : types) {
                        if (type.equalsIgnoreCase("video/mpeg2")) {
                            hasMpeg2Decoder = true;
                            break;
                        }
                    }
                }
                if (hasMpeg2Decoder) break;
            }

            if (!hasMpeg2Decoder) {
                Log.e(TAG, "No MPEG-2 decoder found on this device.");
                return;
            }

            // 创建MediaCodec实例
            mediaCodec = MediaCodec.createDecoderByType("video/mpeg2");
            MediaFormat format = MediaFormat.createVideoFormat("video/mpeg2", 720, 576); // 根据实际分辨率调整
            mediaCodec.configure(format, holder.getSurface(), null, 0);
            mediaCodec.start();

            startDecodingThread();
        } catch (IOException e) {
            Log.e(TAG, "Failed to configure MediaCodec", e);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (mediaCodec != null) {
            mediaCodec.stop();
            mediaCodec.release();
            mediaCodec = null;
        }
        isDecoding = false;
    }

    private void startServerThread() {
        serverThread = new Thread(() -> {
            try (ServerSocket serverSocket = new ServerSocket(22000)) { // 监听端口1234
                Log.d(TAG, "Server started on port 1234");

                while (!serverThread.isInterrupted()) {
                    Socket clientSocket = serverSocket.accept();
                    Log.d(TAG, "Client connected: " + clientSocket.getInetAddress());

                    InputStream inputStream = clientSocket.getInputStream();
                    byte[] buffer = new byte[2048];

                    while (isDecoding && !clientSocket.isClosed()) {
                        // 读取前两个字节，获取RTP包的长度
                        int bytesRead = inputStream.read(buffer, 0, 2);
                        if (bytesRead != 2) break;

                        int packetLength = ((buffer[0] & 0xFF) << 8) | (buffer[1] & 0xFF);

                        // 确保有足够的缓冲区来存储整个RTP包
                        if (packetLength > buffer.length) {
                            buffer = new byte[packetLength];
                        }

                        // 读取剩余的RTP包数据
                        bytesRead = inputStream.read(buffer, 2, packetLength - 2);
                        if (bytesRead != packetLength - 2) break;

                        // 组合成完整的RTP包
                        byte[] rtpPacket = new byte[packetLength];
                        System.arraycopy(buffer, 0, rtpPacket, 0, packetLength);

                        // 解封装RTP数据包
                        byte[] psData = parseRtpPacket(rtpPacket, packetLength);

                        synchronized (this) {
                            psByteBuffer = ByteBuffer.wrap(psData);
                            notifyAll(); // 唤醒解码线程
                        }
                    }

                    clientSocket.close();
                }
            } catch (Exception e) {
                Log.e(TAG, "Error in server thread", e);
            }
        });
        serverThread.start();
    }

    private void startDecodingThread() {
        isDecoding = true;
        decoderThread = new Thread(() -> {
            while (isDecoding) {
                synchronized (this) {
                    try {
                        wait(); // 等待唤醒
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        return;
                    }
                }

                if (psByteBuffer != null) {
                    // 将PS数据提交给MediaCodec进行解码
                    ByteBuffer[] inputBuffers = mediaCodec.getInputBuffers();
                    int inputBufferIndex = mediaCodec.dequeueInputBuffer(-1);
                    if (inputBufferIndex >= 0) {
                        ByteBuffer inputBuffer = inputBuffers[inputBufferIndex];
                        inputBuffer.clear();
                        inputBuffer.put(psByteBuffer.array());
                        mediaCodec.queueInputBuffer(inputBufferIndex, 0, psByteBuffer.limit(), System.nanoTime(), 0);
                    }

                    // 获取解码后的输出缓冲区
                    MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
                    int outputBufferIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, 0);
                    while (outputBufferIndex >= 0) {
                        mediaCodec.releaseOutputBuffer(outputBufferIndex, true);
                        outputBufferIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, 0);
                    }
                }
            }
        });
        decoderThread.start();
    }

    private byte[] parseRtpPacket(byte[] rtpPacket, int length) {
        // 检查数据包长度是否至少包含前14个字节（RTP头部）
        if (length <= 14) {
            throw new IllegalArgumentException("Invalid RTP packet length: " + length);
        }

        // 去掉前14个字节（RTP头部）
        byte[] psData = new byte[length - 14];
        System.arraycopy(rtpPacket, 14, psData, 0, psData.length);

        Log.d(TAG, "Parsed PS data size: " + psData.length);
        return psData;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isDecoding = false;
        if (decoderThread != null) {
            decoderThread.interrupt();
        }
        if (serverThread != null) {
            serverThread.interrupt();
        }
    }

}
